<template>
    <div class="content-panel">
        <div class="space-between v-center mb-4">
            <span class="page-title v-center d-flex mb-0 cursor-pointer" @click="editApps">
                <span>快捷应用</span>
                <el-icon class="ml-1"><Setting /></el-icon>
            </span>
            <el-link type="primary" @click="go('/workbench/apps')">更多应用...</el-link>
        </div>

        <template v-if="!apps.length">
            <div class="remark align-center">暂无快捷应用，<el-link type="primary" @click="editApps">点击</el-link>添加</div>

            <div class="mt-10 mb-4">是否要使用？</div>
            <div class="other-apps app-items">
                <div v-for="item in maybeApps" :key="item.id" class="app-item d-flex cursor-pointer px-2 py-4" @click="goApp(item)">
                    <el-icon class="icon"><component :is="item.icon" /></el-icon>
                    <div class="d-flex-col h-100">
                        <div class="app-title mb-2 font-bold">{{ item.name }}</div>
                        <div class="app-remark flex-auto color-gray">{{ item.remark }}</div>
                    </div>
                </div>
            </div>
        </template>

        <div class="app-items" v-else>
            <div v-for="item in apps" :key="item.id" class="app-item d-flex cursor-pointer px-2 py-4" @click="goApp(item)">
                <el-icon class="icon"><component :is="item.icon" /></el-icon>
                <div class="d-flex-col h-100">
                    <div class="app-title mb-2 font-bold">{{ item.name }}</div>
                    <div class="app-remark flex-auto color-gray">{{ item.remark }}</div>
                </div>
            </div>
        </div>

        <el-dialog v-model="visible" title="配置快捷应用">
            <el-splitter>
                <el-splitter-panel size="400px">
                    <div class="page-title">未添加应用</div>
                    <div v-if="!notAddApps.length" class="remark text-center mt-4">所有应用均已添加</div>
                    <div class="dialog-apps">
                        <div v-for="app in notAddApps" class="app-item d-flex-col cursor-pointer" @click="addApp(app)" title="点击添加">
                            <el-icon class="icon"><component :is="app.icon" /></el-icon>
                            <span>{{ app.name }}</span>
                        </div>
                    </div>
                    <div class="remark ml-4 font-normal v-center">
                        <el-icon><InfoFilled /></el-icon>
                        点击左侧应用可添加至右侧
                    </div>
                </el-splitter-panel>
                <el-splitter-panel>
                    <div class="ml-4">
                        <div class="page-title">
                            <span>已添加应用</span>
                        </div>
                        <div v-if="!addedApps.length" class="remark text-center mt-4 pt-4">暂未添加应用，点击左侧应用进行添加</div>
                        <draggable :list="addedApps" itemKey="id" class="dialog-apps">
                            <template #item="{ element: item, index }">
                                <div class="app-item d-flex-col cursor-pointer" @click="removeApp(item)" title="点击移除">
                                    <el-icon class="icon"><component :is="item.icon" /></el-icon>
                                    <span>{{ item.name }}</span>
                                </div>
                            </template>
                        </draggable>

                        <div class="remark ml-4 font-normal v-center" v-if="addedApps.length">
                            <el-icon><InfoFilled /></el-icon>
                            点击应用可进行移除，拖动可进行排序
                        </div>
                    </div>
                </el-splitter-panel>
            </el-splitter>

            <template #footer>
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="saveOftenApps">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { useSysStore } from "@/store/index";
import * as _ from "lodash";
import draggable from "vuedraggable";

const router = useRouter();
const sysStore = useSysStore();
const userInfo = computed(() => {
    return sysStore.getUserInfo();
});
const apps = ref([]);
const maybeApps = ref([]);
const visible = ref(false);
const allApps = ref([]);
const addedApps = ref([]);

// 未配置快捷入口的应用
const notAddApps = computed(() => {
    let configedAppIds = addedApps.value.map((item) => item.id);
    return allApps.value.filter((item) => !configedAppIds.includes(item.id));
});

onMounted(() => {
    app.https.get("/sys/app/mine").then((resp) => {
        allApps.value = resp;

        let items = resp.sort((o1, o2) => {
            let c1 = o1.usedCount;
            let c2 = o2.usedCount;
            if (c1 == c2) {
                return 0;
            } else if (c1 > c2) {
                return -1;
            } else {
                return 1;
            }
        });
        if (items.length > 3) {
            items = items.slice(0, 3);
        }
        maybeApps.value = items;

        // 处理已配置应用
        let appMap = {};
        resp.forEach((item) => (appMap[item.id] = item));
        let appIds = userInfo.value.metadata?.apps || [];
        apps.value = appIds.map((id) => appMap[id]).filter((item) => !!item);
    });
});

function goApp(item) {
    app.https.get("/sys/app/add-used-count", { id: item.id }, { showError: false });

    if (item.url && item.url.startsWith("http")) {
        // 外部地址，需要先获取code
        app.https.get("/sys/app/auth/code").then((resp) => {
            let target = "_self";
            if (item.openType == "new") {
                target = "_blank";
            }
            window.open(`${item.url}?code=` + resp, target);
        });
        return;
    }
    router.push(`/${item.url || item.code}`);
}

// 配置快捷应用
function editApps() {
    addedApps.value = _.cloneDeep(apps.value);
    visible.value = true;
}

function addApp(item) {
    addedApps.value.push(item);
}

function removeApp(item) {
    let idx = addedApps.value.indexOf(item);
    addedApps.value.splice(idx, 1);
}

function saveOftenApps() {
    let appIds = addedApps.value.map((item) => item.id);
    let metadata = { ...userInfo.value.metadata };
    metadata.apps = appIds;
    app.https.post("/sys/user/update-mine", { metadata }).then(() => {
        app.success("操作成功");
        userInfo.value.metadata = metadata;
        apps.value = addedApps.value;
        visible.value = false;
    });
}

function go(path) {
    router.push(path);
}
</script>

<style lang="scss" scoped>
.app-items {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 16px;

    .app-item {
        --bg_color1: var(--main_bg_color);
        --bg_color2: var(--sub_bg_color);
        align-items: flex-start;
        border-radius: 10px;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        background: linear-gradient(135deg, var(--bg_color1) 0%, var(--bg_color2) 70%);
        box-shadow: 0 0 5px var(--main_shadow_color);
        box-sizing: border-box;

        .app-title {
            font-size: 16px;
        }

        .icon {
            font-size: 30px;
            color: #777;
            margin: 0 18px 0 12px;
        }

        &:hover {
            transform: scale(1.07);
        }
    }
}

:root.theme_default {
    .app-item {
        &:nth-child(5n + 1) {
            --bg_color2: #fff2ff22;
        }

        &:nth-child(5n + 2) {
            --bg_color2: #eeeeff22;
        }

        &:nth-child(5n + 3) {
            --bg_color2: #eeffee22;
        }

        &:nth-child(5n + 4) {
            --bg_color2: #ffeeff22;
        }
    }
}

.dialog-apps {
    display: grid;
    grid-template-columns: repeat(auto-fill, 100px);
    grid-template-rows: repeat(auto-fill, 80px);
    gap: 16px;
    max-height: 500px;
    overflow-y: auto;

    .app-item {
        align-items: center;

        .icon {
            font-size: 30px;
        }
    }
}
</style>
